import Cookie from "js-cookie";
import Vue from 'vue';

export default {
    namespaced: true,
    state: {
        ws: null,
        connected: false,
        messages: [],
    },
    mutations: {
        SET_CONNECTION(state, isConnected) {
            state.connected = isConnected;
        },
        ADD_MESSAGE(state, message) {
            state.messages.push(message);
        },
        SET_WS_INSTANCE(state, wsInstance) {
            state.ws = wsInstance;
        }
    },
    actions: {
        initWebSocket({commit, state}) {
            const self = this; // 保存当前的store实例
            if (!state.ws) {
                const userId = Cookie.get("userId");
                const ws = new WebSocket(`ws://${Vue.prototype.$config.websocketUrl}?token=` + userId);

                ws.onopen = () => {
                    commit('SET_CONNECTION', true);
                };

                ws.onmessage = (event) => {
                    const message = JSON.parse(event.data);
                    commit('ADD_MESSAGE', message);
                };

                ws.onerror = (error) => {
                    console.error('WebSocket error:', error);
                };

                ws.onclose = () => {
                    commit('SET_CONNECTION', false);
                    // 使用保存下来的self变量
                    setTimeout(() => {
                        self.dispatch('initWebSocket');
                    }, 5000); // 简单示例，5秒后尝试重连
                };

                commit('SET_WS_INSTANCE', ws);
            }
        },
        sendMessage({state}, message) {
            if (state.ws && state.connected) {
                state.ws.send(JSON.stringify(message));
            } else {
                console.warn('WebSocket is not connected, cannot send message.');
            }
        },
        closeWebSocket({state, commit}) {
            if (state.ws && state.connected) {
                state.ws.close();
                commit('SET_WS_INSTANCE', null);
            }
        },
    },
};